/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.ProductType;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author natalia
 *
 */
public class ProductTypeDAO {
	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public ProductTypeDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one productType by Id
	 * @param id
	 * @return productType
	 */
	 @Transactional(readOnly = true)
	public ProductType selectById(int id) {
		 ProductType productType = (ProductType) getSession().get(ProductType.class, id);
	    return productType;
	}

	/*
	 * retrieves all productTypes from db
	 * @return List of productTypes
	 */
	 @Transactional(readOnly = true)
	public List<ProductType> selectAll() {
	 
	    List<ProductType> delegations = getSession().createQuery("from productType").list();
	    return delegations;
	}
	
	/*
	 * retrieves all productType from db
	 * @return List of productType
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<ProductType> delegations = getSession().createQuery("from productType").list();
	    return delegations.size();
	}

	/*
	 * inserts a new productType in database
	 * retrieves generated id and sets to productType instance
	 * @param new productType
	 */
	 @Transactional
	public void insert(ProductType productType) {
	    Integer id = (Integer) getSession().save(productType);
	    productType.setId(id);           
	}

	/*
	 * updates productType
	 * @param productType to update
	 */
	 @Transactional
	public void update(ProductType productType) {
		getSession().merge(productType);
	}

	/*
	 * delete given productType
	 * @param productType to delete
	 */
	 @Transactional
	public void delete(ProductType productType) {
		getSession().delete(productType);
	}

	 @Transactional
	public void saveOrUpdate(ProductType productType) {

		getSession().saveOrUpdate(productType);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 ProductType productType = (ProductType) getSession().load(ProductType.class,id);
		 getSession().delete(productType);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<ProductType> search(String name) {
		   Query query = getSession().createQuery("from productType p where p.name like :name");
         query.setParameter("name", "%"+name+"%");
         
         List<ProductType> productTypes = query.list();
		
         return productTypes;
	}
}
